package com.bsoft.rxjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void onclick(View view) {
        Observable<String> observable = getObservable();
        //第一种方法
//        Observer<String> observer = getObserver();
//
//        observable.subscribe(observer);
        //第二种方法

        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                //相当于onNext
                Log.e("OnNext",s+"");
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                //相当于onerror
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                //对应onComplete
            }
        });
    }

    public Observable<String> getObservable() {
        return Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext("呵呵");
                e.onNext("hehe");
                e.onComplete();
            }
        });
    }


    public Observer<String> getObserver() {
        return new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("MainActivity", "onSubscribe");
            }

            @Override
            public void onNext(String value) {
                Log.e("MainActivity", "onNext");

            }

            @Override
            public void onError(Throwable e) {
                Log.e("MainActivity", "onError");

            }

            @Override
            public void onComplete() {
                Log.e("MainActivity", "onComplete");

            }
        };
    }

}
